<template>
  <view class="container">

    <!-- 日期选择 -->
    <view class="date-section">
      <scroll-view scroll-x="true" class="date-scroll">
        <view class="date-list">
          <view v-for="(date, index) in roomInfo.show_time" :key="index" class="date-item"
            :class="selectedDate === date.date ? 'date-active' : ''" @tap="selectDate(date.date)">
            <text class="date-text">{{ date.date }}</text>
            <text class="day-text">{{ date.weekday }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 时间段可视化 -->
    <view class="time-slots-section">
      <view class="slots-container">
        <view class="slots-row">
          <view v-for="(slot, index) in timeSlots" :key="index" class="slot-item" :class="{
            'slot-selected': slot.isSelected,
            'slot-unavailable': slot.isUnavailable,
            'slot-available': !slot.isSelected && !slot.isUnavailable
          }"></view>
        </view>
      </view>

      <view class="slots-container" style="margin-bottom: 20rpx;font-size: 20rpx;">
        <view class="slots-row">
          <view v-for="(slot, index) in timeSlots" :key="index" class="slot-item">{{ slot.hours }}</view>
        </view>
      </view>

      <view class="legend">
        <view class="legend-item">
          <view class="legend-color legend-unavailable"></view>
          <text class="legend-text">不可预定时段</text>
        </view>
        <view class="legend-item">
          <view class="legend-color legend-available"></view>
          <text class="legend-text">可预定时段</text>
        </view>
        <view class="legend-item">
          <view class="legend-color legend-selected"></view>
          <text class="legend-text">当前预定时段</text>
        </view>
      </view>
    </view>

    <!-- 开始时间选择 - 改为picker -->
    <view class="time-selection">
      <view class="time-row">
        <text class="label">预定时间：</text>
        <text class="date">{{ selectedDate }}</text>
        <picker mode="time" :value="startTime" @change="onTimeChange" class="time-picker">
          <view class="time-btn time-start">
            <text>{{ startTime }} ✏️</text>
          </view>
        </picker>
        <text class="to">至</text>
        <view class="time-btn time-end">
          <text>{{ endTime }}</text>
          <text v-if="isCrossDay" class="cross-day">(次日)</text>
        </view>
      </view>
      <view v-if="totalHours > 0" class="duration-info">
        <text class="duration-text">
          预定时长：{{ totalHours }}小时
          <text v-if="isCrossDay" class="cross-day">(跨天)</text>
        </text>
      </view>
    </view>

    <!-- 套餐选择 - 修改为单选模式 -->
    <view class="package-section">
      <view class="package-header">
        <text class="package-title">选择套餐</text>
        <text class="package-tip">温馨提示：只能选择一个套餐，套餐只能在指定的日期、时间内使用</text>
      </view>

      <view class="package-list">
        <view v-for="(pkg, index) in roomPackage" :key="pkg.id" class="package-item"
          :class="selectedPackageId === pkg.id ? 'package-active' : ''" @tap="selectPackage(pkg.id)">
          <view class="package-content">
            <view class="package-left">
              <view class="package-radio">
                <view class="radio-btn" :class="selectedPackageId === pkg.id ? 'radio-active' : ''">
                  <text v-if="selectedPackageId === pkg.id" class="radio-check">✓</text>
                </view>
              </view>
              <view class="package-info">
                <text class="package-name">{{ pkg.name }}</text>
                <text class="package-duration">使用时段：00:00-次日00:00</text>
                <text class="package-validity">有效日期：周一至周日</text>
                <text class="package-times">时长：{{ pkg.times }}小时</text>
              </view>
            </view>
            <view class="package-right">
              <text class="package-price">¥ {{ parseFloat(pkg.money || pkg.price || 0).toFixed(2) }}</text>
              <view v-if="selectedPackageId === pkg.id" class="quantity-controls">
                <view class="quantity-btn quantity-minus" :class="selectedQuantity === 1 ? 'btn-disabled' : ''"
                  @tap.stop="updateQuantity(-1)">
                  <text class="btn-text">-</text>
                </view>
                <text class="quantity">{{ selectedQuantity }}</text>
                <view class="quantity-btn quantity-plus" @tap.stop="updateQuantity(1)">
                  <text class="btn-text">+</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠券 - 完善逻辑 -->
    <!-- <view class="coupon-section" @tap="goToCouponList">
      <view class="coupon-row">
        <view class="coupon-left">
          <view class="coupon-icon">🎫</view>
          <text class="coupon-label">优惠券</text>
        </view>
        <view class="coupon-right">
          <text class="coupon-count">{{ availableCoupons.length }} 张可用</text>
          <text class="coupon-arrow">></text>
        </view>
      </view>
      <view v-if="selectedCoupon" class="selected-coupon">
        <text class="selected-coupon-text">已选择：{{ selectedCoupon.name }} -¥{{ selectedCoupon.discount ||
          selectedCoupon.amount }}</text>
      </view>
    </view> -->

    <!-- 修改底部操作栏，移除立即购买逻辑 -->
    <view class="bottom-bar">
      <view class="price-total">
        <text v-if="selectedCoupon" class="original-price">原价：¥ {{ totalPrice.toFixed(2) }}</text>
        <text class="total-price">{{ selectedCoupon ? '优惠后：' : '' }}¥ {{ finalPrice.toFixed(2) }}</text>
      </view>
      <view class="action-buttons">
        <button class="member-btn" @tap="goToRecharge">会员优惠</button>
        <button class="buy-btn" :disabled="!selectedPackageId" @tap="goToSettlement">去结算</button>
      </view>
      <view class="home-indicator"></view>
    </view>
  </view>
</template>

<script>
import request from '@/common/request.js';
import { mapGetters, mapActions, mapState } from 'vuex';

export default {
  data() {
    return {
      shopId: '',
      roomId: '',
      roomInfo: {},
      roomPackage: [],
      selectedDate: '',
      selectedPackageId: '', // 选中的套餐ID
      selectedQuantity: 1, // 选中套餐的数量
      showTimeSelector: false,
      startTime: '09:41',
      timeSlots: [],
      availableCoupons: [], // 可用优惠券列表
      selectedCoupon: null, // 选中的优惠券

      // 保存页面状态，用于从优惠券页面返回时恢复
      pageState: {
        selectedPackageId: '',
        selectedQuantity: 1,
        selectedDate: '',
        startTime: '',
        totalPrice: 0
      },

      // 标记数据是否已加载完成
      isDataLoaded: false,
      // 标记是否是首次加载
      isFirstLoad: true
    }
  },
  computed: {
    // 修改：基于单个套餐计算总小时数
    totalHours() {
      if (!this.selectedPackageId || !this.roomPackage.length) return 0;

      const selectedPackage = this.roomPackage.find(pkg => pkg.id == this.selectedPackageId);
      if (!selectedPackage) return 0;

      return this.selectedQuantity * (parseInt(selectedPackage.times) || 0);
    },
    endTimeResult() {
      return this.calculateEndTime(this.startTime, this.totalHours)
    },
    endTime() {
      return this.endTimeResult.time || this.startTime
    },
    isCrossDay() {
      return this.endTimeResult.isCrossDay || false
    },
    // 修改：基于单个套餐计算总价格
    totalPrice() {
      if (!this.selectedPackageId || !this.roomPackage.length) return 0;

      const selectedPackage = this.roomPackage.find(pkg => pkg.id == this.selectedPackageId);
      if (!selectedPackage) return 0;

      // 确保价格转换正确
      const price = parseFloat(selectedPackage.money || selectedPackage.price || 0);
      return this.selectedQuantity * price;
    },
    // 新增：计算最终价格（扣除优惠券）
    finalPrice() {
      let price = this.totalPrice;
      if (this.selectedCoupon) {
        const discount = parseFloat(this.selectedCoupon.discount || this.selectedCoupon.amount || 0);
        price = Math.max(0, price - discount);
      }
      return price;
    }
  },
  onLoad(options) {
    console.log('onLoad - 页面加载参数:', options);

    this.roomId = options.roomId || ''
    this.shopId = options.shopId || ''
    this.isFirstLoad = true;

    // 处理参数并初始化数据
    this.handlePageParams(options);
  },

  // 修改：页面显示时的处理
  onShow() {
    console.log('onShow - 页面显示，当前状态:', {
      selectedPackageId: this.selectedPackageId,
      selectedQuantity: this.selectedQuantity,
      selectedCoupon: this.selectedCoupon,
      isDataLoaded: this.isDataLoaded,
      isFirstLoad: this.isFirstLoad
    });

    // 如果不是首次加载，说明是从其他页面返回，需要处理参数
    if (!this.isFirstLoad) {
      this.handleReturnFromOtherPage();
    }

    this.isFirstLoad = false;
  },

  methods: {
    // 新增：处理从其他页面返回的情况
    handleReturnFromOtherPage() {
      // 获取当前页面实例和参数
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options || {};

      console.log('从其他页面返回，当前页面参数:', options);

      // 如果有参数，说明是从优惠券页面返回，需要恢复状态
      if (Object.keys(options).length > 0 && (options.selectedPackageId || options.selectedCoupon)) {
        this.handlePageParams(options);
      } else if (this.isDataLoaded && this.selectedPackageId && this.roomInfo.hours) {
        // 如果没有新参数但数据已加载，重新生成时间段
        this.$nextTick(() => {
          this.generateAndUpdateTimeSlots();
        });
      }
    },

    // 新增：统一处理页面参数
    async handlePageParams(options) {
      console.log('处理页面参数:', options);

      // 保存需要恢复的状态
      const pendingState = {
        selectedPackageId: options.selectedPackageId || '',
        selectedQuantity: parseInt(options.selectedQuantity) || 1,
        selectedDate: options.selectedDate || '',
        startTime: options.startTime || '',
        selectedCoupon: null
      };

      // 处理从优惠券页面返回的情况
      if (options.selectedCoupon) {
        try {
          pendingState.selectedCoupon = JSON.parse(decodeURIComponent(options.selectedCoupon));
          console.log('准备恢复选中的优惠券:', pendingState.selectedCoupon);
        } catch (e) {
          console.error('解析优惠券数据失败:', e);
        }
      }

      // 如果没有传入时间，使用当前时间
      if (!pendingState.startTime) {
        const now = new Date()
        const hours = now.getHours().toString().padStart(2, '0')
        const minutes = now.getMinutes().toString().padStart(2, '0')
        pendingState.startTime = `${hours}:${minutes}`
      }

      // 先设置基本信息
      this.startTime = pendingState.startTime;
      this.selectedDate = pendingState.selectedDate;

      // 如果数据还未加载，先加载数据
      if (!this.isDataLoaded) {
        await this.initPageData();
      }

      // 应用状态
      this.applyStateFromParams(pendingState);
    },

    // 新增：从参数应用状态
    applyStateFromParams(pendingState) {
      console.log('应用参数状态:', pendingState);

      // 恢复套餐选择状态
      if (pendingState.selectedPackageId && this.roomPackage.length > 0) {
        const packageExists = this.roomPackage.find(pkg => pkg.id == pendingState.selectedPackageId);
        if (packageExists) {
          this.selectedPackageId = pendingState.selectedPackageId;
          this.selectedQuantity = pendingState.selectedQuantity;
          console.log('恢复套餐选择:', packageExists);
        }
      }

      // 恢复优惠券状态
      if (pendingState.selectedCoupon) {
        this.selectedCoupon = pendingState.selectedCoupon;
        console.log('恢复优惠券选择:', this.selectedCoupon);
      }

      // 恢复日期和时间
      if (pendingState.selectedDate) {
        this.selectedDate = pendingState.selectedDate;
      }
      if (pendingState.startTime) {
        this.startTime = pendingState.startTime;
      }

      // 重新生成时间段
      this.$nextTick(() => {
        this.generateAndUpdateTimeSlots();
      });
    },

    // 新增：初始化页面数据
    async initPageData() {
      try {
        console.log('开始初始化页面数据...');

        // 先获取房间信息
        await this.getRoomInfo();
        // 然后获取套餐信息
        await this.getRoomPackages();

        // 标记数据已加载完成
        this.isDataLoaded = true;
        console.log('页面数据初始化完成');

      } catch (error) {
        console.error('初始化页面数据失败:', error);
      }
    },

    // 保存页面状态
    savePageState() {
      this.pageState = {
        selectedPackageId: this.selectedPackageId,
        selectedQuantity: this.selectedQuantity,
        selectedDate: this.selectedDate,
        startTime: this.startTime,
        totalPrice: this.totalPrice
      };
    },

    // 修改：跳转到优惠券列表 - 保存当前状态
    goToCouponList() {
      // 保存当前页面状态
      this.savePageState();

      const params = {
        totalPrice: this.totalPrice,
        roomId: this.roomId,
        shopId: this.shopId,
        selectedPackageId: this.selectedPackageId,
        selectedQuantity: this.selectedQuantity,
        selectedDate: this.selectedDate,
        startTime: this.startTime,
        // 如果已有选中的优惠券，也传递过去
        ...(this.selectedCoupon && { selectedCoupon: this.selectedCoupon })
      };

      console.log('跳转到优惠券页面，传递参数:', params);

      uni.navigateTo({
        url: `/pages/shop/coupon-list?params=${encodeURIComponent(JSON.stringify(params))}`
      });
    },

    // 修改：获取房间信息 - 返回Promise
    getRoomInfo(targetDate) {
      return new Promise((resolve, reject) => {
        let opts = {
          url: `/api/shop/roomInfo?id=${this.roomId}&time=${targetDate || this.selectedDate}`,
          method: 'get',
        };
        request.httpRequest(opts).then(res => {
          if (res && res.data && res.data.data) {
            this.roomInfo = res.data.data;

            if (!targetDate && !this.selectedDate && res.data.data.show_time && res.data.data.show_time.length > 0) {
              this.selectedDate = res.data.data.show_time[0].date;
            } else if (targetDate) {
              this.selectedDate = targetDate;
            }
          }

          this.$nextTick(() => {
            this.generateAndUpdateTimeSlots();
          });

          resolve();
        }).catch(err => {
          console.error('获取房间信息失败:', err);
          uni.showToast({
            title: '获取房间信息失败',
            icon: 'none'
          });
          reject(err);
        });
      });
    },

    // 修改：获取套餐信息 - 返回Promise
    getRoomPackages() {
      return new Promise((resolve, reject) => {
        if (!this.roomInfo || !this.roomInfo.room_info || !this.roomInfo.room_info.id) {
          resolve();
          return;
        }

        let opts = {
          url: `/api/shop/getRoomPackage?id=${this.roomInfo.room_info.id}`,
          method: 'get',
        };
        request.httpRequest(opts).then(res => {
          if (res && res.data && res.data.data && Array.isArray(res.data.data)) {
            this.roomPackage = res.data.data;
            console.log('套餐数据加载完成:', this.roomPackage);
          } else {
            this.roomPackage = [];
          }
          resolve();
        }).catch(err => {
          console.error('获取套餐失败:', err);
          this.roomPackage = [];
          reject(err);
        });
      });
    },

    // 新增：选择套餐方法
    selectPackage(packageId) {
      console.log('选择套餐:', packageId);

      if (this.selectedPackageId === packageId) {
        // 如果点击的是已选中的套餐，则取消选择
        this.selectedPackageId = '';
        this.selectedQuantity = 1;
      } else {
        // 选择新套餐
        this.selectedPackageId = packageId;
        this.selectedQuantity = 1;
      }

      // 保存状态
      this.savePageState();

      this.$nextTick(() => {
        this.generateAndUpdateTimeSlots();
      });
    },

    // 修改：更新数量方法（只针对选中的套餐）
    updateQuantity(change) {
      if (!this.selectedPackageId) return;

      const newQuantity = Math.max(1, this.selectedQuantity + change);
      this.selectedQuantity = newQuantity;

      // 保存状态
      this.savePageState();

      this.$nextTick(() => {
        this.generateAndUpdateTimeSlots();
      });
    },

    calculateEndTime(start, hours) {
      if (!start || hours <= 0) {
        return { time: start, isCrossDay: false }
      }

      const timeParts = start.split(':');
      const startHour = parseInt(timeParts[0]);
      const startMinute = parseInt(timeParts[1]);

      const startDate = new Date();
      startDate.setHours(startHour, startMinute, 0, 0);

      const endDate = new Date(startDate.getTime() + hours * 60 * 60 * 1000);
      const endHour = endDate.getHours().toString().padStart(2, '0');
      const endMinute = endDate.getMinutes().toString().padStart(2, '0');

      const isCrossDay = endDate.getDate() > startDate.getDate() ||
        endDate.getMonth() > startDate.getMonth() ||
        endDate.getFullYear() > startDate.getFullYear();

      return {
        time: endHour + ':' + endMinute,
        isCrossDay: isCrossDay,
      }
    },

    generateAndUpdateTimeSlots() {
      if (!this.roomInfo || !this.roomInfo.hours || !Array.isArray(this.roomInfo.hours)) {
        this.timeSlots = [];
        return;
      }

      const totalBookedHours = this.totalHours;
      console.log('生成时间段，总预定小时数:', totalBookedHours);

      const slots = [];
      this.roomInfo.hours.forEach((time, index) => {
        const isCurrentlySelected = this.isTimeSlotSelected(index, totalBookedHours);

        slots.push({
          hours: time.hours,
          hour: time.hours,
          displayHour: `${String(time.hours).padStart(2, '0')}:00`,
          isBooked: time.selected == 1,
          isUnavailable: time.selected == 1,
          isSelected: isCurrentlySelected,
          originalData: time
        });
      });

      this.timeSlots = slots;
      console.log('时间段生成完成:', this.timeSlots.filter(slot => slot.isSelected).length, '个选中');
    },

    findStartSlotIndex() {
      if (!this.startTime || !this.roomInfo || !this.roomInfo.hours) {
        return -1;
      }

      const [startHour, startMinute] = this.startTime.split(':').map(Number);

      for (let i = 0; i < this.roomInfo.hours.length; i++) {
        const timeSlot = this.roomInfo.hours[i];
        const slotHour = timeSlot.hours;

        if (slotHour === startHour) {
          return i;
        }
      }

      let closestIndex = -1;
      let minDiff = Infinity;

      for (let i = 0; i < this.roomInfo.hours.length; i++) {
        const timeSlot = this.roomInfo.hours[i];

        if (timeSlot.selected == 1) {
          continue;
        }

        const diff = Math.abs(timeSlot.hours - startHour);
        if (diff < minDiff) {
          minDiff = diff;
          closestIndex = i;
        }
      }

      return closestIndex;
    },

    getAvailableSlotsFromStart(startIndex, neededHours) {
      if (!this.roomInfo || !this.roomInfo.hours) return [];

      const selectedSlots = [];
      let hoursCollected = 0;
      const totalSlots = this.roomInfo.hours.length;
      let currentDay = 0;

      while (hoursCollected < neededHours) {
        let dayStartIndex = currentDay === 0 ? startIndex : 0;
        let slotsAddedThisDay = 0;

        for (let i = dayStartIndex; i < totalSlots && hoursCollected < neededHours; i++) {
          const currentSlot = this.roomInfo.hours[i];

          if (currentSlot.selected != 1) {
            const globalIndex = currentDay * totalSlots + i;
            selectedSlots.push(globalIndex);
            hoursCollected++;
            slotsAddedThisDay++;
          }
        }

        if (slotsAddedThisDay === 0 && dayStartIndex === 0) {
          break;
        }

        currentDay++;

        if (currentDay >= 7) {
          break;
        }
      }

      if (hoursCollected >= neededHours) {
        return selectedSlots;
      } else {
        return [];
      }
    },

    isTimeSlotSelected(slotIndex, totalBookedHours) {
      if (totalBookedHours <= 0 || !this.startTime) {
        return false;
      }

      const startSlotIndex = this.findStartSlotIndex();
      if (startSlotIndex === -1) {
        return false;
      }

      const selectedSlots = this.getAvailableSlotsFromStart(startSlotIndex, totalBookedHours);
      const totalSlots = this.roomInfo?.hours?.length || 0;

      for (let day = 0; day < 7; day++) {
        const globalIndex = day * totalSlots + slotIndex;
        if (selectedSlots.includes(globalIndex)) {
          return true;
        }
      }

      return false;
    },

    selectDate(date) {
      this.selectedDate = date;
      this.savePageState();
      this.getRoomInfo(date);
    },

    onTimeChange(e) {
      this.startTime = e.detail.value;
      this.savePageState();
      this.$nextTick(() => {
        this.generateAndUpdateTimeSlots();
      });
    },

    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    // 新增：计算结束日期时间
    calculateEndDateTime() {
      if (!this.selectedDate || !this.startTime || this.totalHours <= 0) {
        return this.formatFullDateTime(this.selectedDate, this.startTime);
      }

      // 解析开始日期和时间
      const startDateTime = this.formatFullDateTime(this.selectedDate, this.startTime);
      const startDate = new Date(startDateTime);

      // 添加小时数
      const endDate = new Date(startDate.getTime() + this.totalHours * 60 * 60 * 1000);

      // 格式化结束时间
      const endYear = endDate.getFullYear();
      const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
      const endDay = String(endDate.getDate()).padStart(2, '0');
      const endHour = String(endDate.getHours()).padStart(2, '0');
      const endMinute = String(endDate.getMinutes()).padStart(2, '0');

      return `${endYear}-${endMonth}-${endDay} ${endHour}:${endMinute}`;
    },

    // 修改：跳转到结算页面 - 传递完整的状态信息
    // 新增：跳转到结算页面
    goToSettlement() {
      if (!this.selectedPackageId) {
        uni.showToast({
          title: '请选择套餐',
          icon: 'none'
        });
        return;
      }

      const totalBookedHours = this.totalHours;
      if (totalBookedHours === 0) {
        uni.showToast({
          title: '请选择套餐',
          icon: 'none'
        });
        return;
      }

      const startSlotIndex = this.findStartSlotIndex();
      if (startSlotIndex === -1) {
        uni.showToast({
          title: '请选择有效的开始时间',
          icon: 'none'
        });
        return;
      }

      const availableSlots = this.getAvailableSlotsFromStart(startSlotIndex, totalBookedHours);
      if (availableSlots.length === 0) {
        uni.showToast({
          title: `从${this.startTime}开始没有足够的可用时间段，需要${totalBookedHours}小时`,
          icon: 'none',
          duration: 3000
        });
        return;
      }

      // 计算结束时间
      const endTimeResult = this.calculateEndTime(this.startTime, totalBookedHours);

      // 正确处理日期格式
      let startDate = this.selectedDate;
      let endDate = this.selectedDate;

      // 确保日期格式正确
      if (startDate.includes('-') && startDate.split('-').length === 2) {
        const currentYear = new Date().getFullYear();
        startDate = `${currentYear}-${startDate}`;
        endDate = `${currentYear}-${endDate}`;
      }

      // 如果跨天，计算结束日期
      if (endTimeResult.isCrossDay) {
        const startDateObj = new Date(startDate);
        startDateObj.setDate(startDateObj.getDate() + 1);
        const endYear = startDateObj.getFullYear();
        const endMonth = String(startDateObj.getMonth() + 1).padStart(2, '0');
        const endDay = String(startDateObj.getDate()).padStart(2, '0');
        endDate = `${endYear}-${endMonth}-${endDay}`;
      }

      // 准备订单数据
      const orderData = {
        roomId: this.roomId,
        packageId: this.selectedPackageId,
        quantity: this.selectedQuantity,
        startDate: startDate,
        startTime: this.startTime,
        endDate: endDate,
        endTime: endTimeResult.time,
        duration: totalBookedHours,
        coupon: this.selectedCoupon // 添加优惠券信息
      };

      // 获取选中套餐的价格
      const selectedPackage = this.roomPackage.find(pkg => pkg.id === this.selectedPackageId);
      const packagePrice = parseFloat(selectedPackage?.money || selectedPackage?.price || 0);

      // 修复跳转URL - 添加缺失的 & 符号
      uni.navigateTo({
        url: `/pages/order/order-reservation?shopId=${this.shopId}&roomId=${this.roomId}&packageId=${this.selectedPackageId}&price=${packagePrice}&totalPrice=${this.totalPrice}&finalPrice=${this.finalPrice}&orderData=${encodeURIComponent(JSON.stringify(orderData))}&timeSlots=${encodeURIComponent(JSON.stringify(this.timeSlots))}`
      });
    },


    // 修复格式化完整日期时间方法
    formatFullDateTime(date, time) {
      let fullDate = date;

      // 处理日期格式
      if (date && date.includes('-')) {
        const dateParts = date.split('-');
        if (dateParts.length === 2) {
          // MM-DD 格式，添加当前年份
          const currentYear = new Date().getFullYear();
          fullDate = `${currentYear}-${dateParts[0]}-${dateParts[1]}`;
        }
        // 如果已经是完整格式，保持不变
      } else {
        // 如果没有有效日期，使用当前日期
        const now = new Date();
        fullDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
      }

      return `${fullDate} ${time}:00`;
    },

    goToRecharge() {
      // 跳转到充值页面
      console.log('跳转到充值页面');
      uni.navigateTo({
        url: '/pages/wallet/recharge'
      });
    }
  }
}
</script>

<style>
/* 保持原有样式不变 */
page {
  background-color: #f5f5f5;
}

.container {
  min-height: 100vh;
  padding-bottom: 200rpx;
}

/* 日期选择 */
.date-section {
  background-color: #fff;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
}

.date-scroll {
  white-space: nowrap;
}

.date-list {
  display: flex;
  padding: 0 30rpx;
}

.date-item {
  display: inline-block;
  padding: 24rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
  text-align: center;
  min-width: 160rpx;
  margin-right: 20rpx;
}

.date-active {
  background-color: #007aff;
  border-color: #007aff;
  color: #fff;
}

.date-text {
  display: block;
  font-size: 24rpx;
  font-weight: 500;
}

.day-text {
  display: block;
  font-size: 24rpx;
  margin-top: 8rpx;
}

/* 时间段可视化 */
.time-slots-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.slots-container {
  /* margin-bottom: 30rpx; */
}

.slots-row {
  display: flex;
  flex-wrap: wrap;
}

.slot-item {
  width: 3.1%;
  height: 32rpx;
  border-radius: 4rpx;
  margin-right: 1%;
  margin-bottom: 8rpx;
}

.slot-selected {
  background-color: #ff6b6b;
}

.slot-unavailable {
  background-color: #007aff;
}

.slot-available {
  background-color: #d0d0d0;
}

.legend {
  display: flex;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
  margin-bottom: 10rpx;
}

.legend-color {
  width: 24rpx;
  height: 24rpx;
  border-radius: 4rpx;
  margin-right: 8rpx;
}

.legend-unavailable {
  background-color: #007aff;
}

.legend-available {
  background-color: #d0d0d0;
}

.legend-selected {
  background-color: #ff6b6b;
}

.legend-text {
  font-size: 24rpx;
  color: #666;
}

/* 时间选择 */
.time-selection {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.time-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.label {
  color: #333;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.date {
  font-weight: 500;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.time-btn {
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.time-start {
  border: 2rpx solid #ff6b6b;
  color: #ff6b6b;
  background-color: #fff;
}

.time-end {
  background-color: #e0e0e0;
  color: #666;
}

.to {
  color: #999;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.cross-day {
  color: #ff6b6b;
  font-size: 24rpx;
}

.duration-info {
  margin-top: 16rpx;
}

.duration-text {
  font-size: 28rpx;
  color: #666;
}

/* 套餐选择 - 修改为单选样式 */
.package-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.package-header {
  margin-bottom: 30rpx;
}

.package-title {
  font-size: 32rpx;
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.package-tip {
  font-size: 24rpx;
  color: #999;
}

.package-list {
  display: flex;
  flex-direction: column;
}

.package-item {
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  cursor: pointer;
}

.package-active {
  border-color: #007aff;
  border-width: 4rpx;
  background-color: #f0f8ff;
}

.package-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.package-left {
  flex: 1;
  display: flex;
  align-items: flex-start;
}

.package-radio {
  margin-right: 20rpx;
  padding-top: 8rpx;
}

.radio-btn {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.radio-active {
  border-color: #007aff;
  background-color: #007aff;
}

.radio-check {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.package-info {
  flex: 1;
}

.package-name {
  font-size: 36rpx;
  font-weight: 500;
  display: block;
  margin-bottom: 16rpx;
}

.package-duration,
.package-validity {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.package-times {
  font-size: 28rpx;
  color: #007aff;
  font-weight: 500;
  display: block;
}

.package-right {
  text-align: right;
}

.package-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b6b;
  display: block;
  margin-bottom: 16rpx;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: #007aff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-disabled {
  opacity: 0.5;
}

.btn-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.quantity {
  font-size: 32rpx;
  font-weight: 500;
  color: #007aff;
  min-width: 64rpx;
  text-align: center;
  margin: 0 16rpx;
}

/* 优惠券样式 - 完善 */
.coupon-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
}

.coupon-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-left {
  display: flex;
  align-items: center;
}

.coupon-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.coupon-label {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.coupon-right {
  display: flex;
  align-items: center;
}

.coupon-count {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
}

.coupon-arrow {
  font-size: 28rpx;
  color: #999;
}

.selected-coupon {
  margin-top: 16rpx;
  padding: 16rpx;
  background-color: #f0f8ff;
  border-radius: 12rpx;
  border-left: 6rpx solid #007aff;
}

.selected-coupon-text {
  font-size: 28rpx;
  color: #007aff;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 30rpx;
  border-top: 2rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-total {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
  margin-bottom: 8rpx;
}

.total-price {
  font-size: 40rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.action-buttons {
  display: flex;
}

.member-btn {
  background-color: #ff9500;
  color: #fff;
  border: none;
  padding: 0 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.buy-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  padding: 0 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.buy-btn[disabled] {
  opacity: 0.5;
}

.home-indicator {
  position: absolute;
  bottom: 16rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 256rpx;
  height: 8rpx;
  background-color: #000;
  border-radius: 4rpx;
}
</style>